﻿using System;
using CNative.Cloud.Caching.Configurations;
using CNative.Cloud.CPlatform;
using CNative.Cloud.CPlatform.Configurations;
//using CNative.Cloud.EventBusKafka;
//using CNative.Cloud.Zookeeper.Configurations;
//using CNative.Cloud.Zookeeper;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
//using CNative.Cloud.System;
using CNative.Cloud.Consul.Configurations;
using CNative.Cloud.EventBusRabbitMQ.Configurations;
using Microsoft.Extensions.Logging;
using Topshelf;
using System.IO;

namespace CNative.Services.Server
{
    public class Program
    {
        static void Main(string[] args)
        {
            string baseDirectory = Cloud.CPlatform.Utilities.EnvironmentHelper.BaseDirectory;

            var builder = new HostBuilder()
                .RegisterMicroServices()
                .ConfigureAppConfiguration((hostContext, configure) =>
                {
                    configure.AddCPlatformFile("${CNativePath}|" + Path.Combine(baseDirectory, "cnativeSettings.json"), optional: false, reloadOnChange: true);
                    configure.AddCacheFile("${cachePath}|" + Path.Combine(baseDirectory, "configs/cacheSettings.json"), optional: false, reloadOnChange: true);
                    configure.AddEventBusFile("${eventBusPath}|" + Path.Combine(baseDirectory, "configs/eventBusSettings.json"), optional: false, reloadOnChange: true);
                    configure.AddConsulFile("${consulPath}|" + Path.Combine(baseDirectory, "configs/consul.json"), optional: false, reloadOnChange: true);
                    //configure.AddZookeeperFile("${zookeeperPath}|"+Path.Combine(ProcessDirectory, "configs/zookeeper.json"), optional: false, reloadOnChange: true);
                })
                .UseServer(options => { })
                .UseClient()
                //.UseDefaultCacheInterceptor()
                //.Build().RunAsync()
                ;

            if (Environment.OSVersion.Platform != PlatformID.Unix
                && Environment.OSVersion.Platform != PlatformID.MacOSX)
            {
                var rc = HostFactory.Run(x =>
               {
                   x.Service<IHost>(s =>
                   {
                       s.ConstructUsing(() => builder.Build());
                       // 当服务启动后执行
                       s.WhenStarted(service =>
                          {
                              service?.RunAsync();
                              //Task.Factory.StartNew(() =>
                              //{
                              //    service?.StartAsync();
                              //});
                          });
                       // 当服务停止后执行
                       s.WhenStopped(service =>
                          {
                              service?.StopAsync();
                          });

                   });
                   x.UseNLog();
                   x.RunAsLocalSystem();

                   x.SetDescription("CNative微服务");
                   x.SetDisplayName("CNative Service");
                   x.SetServiceName("CNative.Service");
                   x.StartAutomaticallyDelayed();
                   x.EnableShutdown();

                   // 设置服务失败后的操作，分别对应第一次、第二次、后续
                   x.EnableServiceRecovery(t =>
                      {
                          t.RestartService(0);
                          t.RestartService(1);
                          t.RestartService(10);
                          t.OnCrashOnly();
                      });

                   x.OnException(ex =>
                   {
                       ConsoleC.WriteLine(ex, " HostFactory.Run ");
                       // Do something with the exception
                   });
               });

                var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());  //11
                Environment.ExitCode = exitCode;
            }
            else
            {
                using (var host = builder.Build())
                {
                    host.Run();
                }
            }
        }
    }
}
